package com.logictech.activity.system.web.back;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.VelocityContext;
import org.jeecgframework.p3.core.common.utils.AjaxJson;
import org.jeecgframework.p3.core.util.MD5Util;
import org.jeecgframework.p3.core.util.SystemTools;
import org.jeecgframework.p3.core.util.plugin.ContextHolderUtils;
import org.jeecgframework.p3.core.util.plugin.ViewVelocity;
import org.jeecgframework.p3.core.utils.common.PageQuery;
import org.jeecgframework.p3.core.web.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.logictech.activity.system.entity.SystemRole;
import com.logictech.activity.system.entity.SystemUser;
import com.logictech.activity.system.service.SystemRoleService;
import com.logictech.activity.system.service.SystemUserService;
import com.logictech.activity.system.vo.LoginUser;

@Controller
@RequestMapping({ "/system/back/systemUser" })
public class SystemUserController extends BaseController {
	@Autowired
	private SystemUserService systemUserService;
	@Autowired
	private SystemRoleService systemRoleService;

	@RequestMapping(value = { "list" }, method = { org.springframework.web.bind.annotation.RequestMethod.GET,
			org.springframework.web.bind.annotation.RequestMethod.POST })
	public void list(@ModelAttribute SystemUser query, HttpServletResponse response, HttpServletRequest request,
			@RequestParam(required = false, value = "pageNo", defaultValue = "1") int pageNo,
			@RequestParam(required = false, value = "pageSize", defaultValue = "10") int pageSize) throws Exception {
		PageQuery<SystemUser> pageQuery = new PageQuery<SystemUser>();
		pageQuery.setPageNo(pageNo);
		pageQuery.setPageSize(pageSize);
		VelocityContext velocityContext = new VelocityContext();
		pageQuery.setQuery(query);
		velocityContext.put("systemUser", query);
		velocityContext.put("pageInfos",
				SystemTools.convertPaginatedList(this.systemUserService.queryPageList(pageQuery)));
		String viewName = "system/back/systemUser-list.vm";
		request.getSession().setAttribute("pageQuerySystemUser", pageQuery);
		ViewVelocity.view(request, response, viewName, velocityContext);
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = { "back" }, method = { org.springframework.web.bind.annotation.RequestMethod.GET,
			org.springframework.web.bind.annotation.RequestMethod.POST })
	public void back(@ModelAttribute SystemUser query, HttpServletResponse response, HttpServletRequest request,
			@RequestParam(required = false, value = "pageNo", defaultValue = "1") int pageNo,
			@RequestParam(required = false, value = "pageSize", defaultValue = "10") int pageSize) throws Exception {
		PageQuery<SystemUser> pageQuery = new PageQuery<SystemUser>();
		
		Object session = request.getSession().getAttribute("pageQuerySystemUser");
		if(session != null){
			pageQuery = (PageQuery<SystemUser>)session;
			query = pageQuery.getQuery();
		}else{
			pageQuery.setPageNo(pageNo);
			pageQuery.setPageSize(pageSize);
			pageQuery.setQuery(query);
		}
		VelocityContext velocityContext = new VelocityContext();
		velocityContext.put("systemUser", query);
		velocityContext.put("pageInfos",
				SystemTools.convertPaginatedList(this.systemUserService.queryPageList(pageQuery)));
		String viewName = "system/back/systemUser-list.vm";
		ViewVelocity.view(request, response, viewName, velocityContext);
	}

	@RequestMapping(value = { "toDetail" }, method = { org.springframework.web.bind.annotation.RequestMethod.GET })
	public void toDetail(@RequestParam(required = true, value = "id") Long id, HttpServletResponse response,
			HttpServletRequest request) throws Exception {
		VelocityContext velocityContext = new VelocityContext();
		String viewName = "system/back/systemUser-detail.vm";
		SystemUser systemUser = this.systemUserService.queryById(id);
		velocityContext.put("systemUser", systemUser);
		ViewVelocity.view(request, response, viewName, velocityContext);
	}

	@RequestMapping(value = { "/toAdd" }, method = { org.springframework.web.bind.annotation.RequestMethod.GET,
			org.springframework.web.bind.annotation.RequestMethod.POST })
	public void toAdd(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws Exception {
		VelocityContext velocityContext = new VelocityContext();
		String viewName = "system/back/systemUser-add.vm";

		List<SystemRole> roleList = this.systemRoleService.queryAllRoleList();
		velocityContext.put("roleList", roleList);
		ViewVelocity.view(request, response, viewName, velocityContext);
	}

	@RequestMapping(value = { "/doAdd" }, method = { org.springframework.web.bind.annotation.RequestMethod.GET,
			org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
	public AjaxJson doAdd(@ModelAttribute SystemUser systemUser,
			@RequestParam(required = false, value = "roleIds") List<String> roleIds) {
		AjaxJson j = new AjaxJson();
		try {
			// 检查user_id是否存在
			LoginUser loginUser = systemUserService.queryUserByUserId(systemUser.getUserId());
			if(loginUser == null){
				LoginUser user = (LoginUser) ContextHolderUtils.getSession().getAttribute("OPERATE_WEB_LOGIN_USER");
				Date date = new Date();
				systemUser.setCreateDt(date);
				systemUser.setEditDt(date);
				systemUser.setCreator(user.getId().toString());
				systemUser.setEditor(user.getId().toString());
				systemUser.setDeleteFlag("0");
				String passwordEncode = MD5Util.MD5Encode(systemUser.getUserId(), "utf-8");
				systemUser.setPassword(passwordEncode);
				this.systemUserService.doAdd(systemUser, roleIds);
				j.setMsg("保存成功");
			}else{
				j.setSuccess(false);
				j.setMsg("用户ID已存在");
			}
		} catch (Exception e) {
			log.info(e.getMessage());
			j.setSuccess(false);
			j.setMsg("保存失败");
		}
		return j;
	}

	@RequestMapping(value = { "toEdit" }, method = { org.springframework.web.bind.annotation.RequestMethod.GET })
	public void toEdit(@RequestParam(required = true, value = "id") Long id, HttpServletResponse response,
			HttpServletRequest request) throws Exception {
		VelocityContext velocityContext = new VelocityContext();
		SystemUser systemUser = this.systemUserService.queryById(id);

		List<String> roleIds = this.systemUserService.queryUserRoles(systemUser.getUserId());

		List<SystemRole> allRolelist = this.systemRoleService.queryAllRoleList();
		List<SystemRole> checkedRoleList = new ArrayList<SystemRole>();
		if ((allRolelist != null) && (allRolelist.size() > 0)) {
			for (SystemRole role : allRolelist) {
				if (roleIds.contains(role.getRoleId())) {
					role.setIsChecked(Boolean.valueOf(true));
				}
				checkedRoleList.add(role);
			}
		}
		velocityContext.put("roleList", checkedRoleList);
		velocityContext.put("systemUser", systemUser);
		String viewName = "system/back/systemUser-edit.vm";
		ViewVelocity.view(request, response, viewName, velocityContext);
	}

	@RequestMapping(value = { "/doEdit" }, method = { org.springframework.web.bind.annotation.RequestMethod.GET,
			org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
	public AjaxJson doEdit(@ModelAttribute SystemUser systemUser,
			@RequestParam(required = false, value = "roleIds") List<String> roleIds) {
		AjaxJson j = new AjaxJson();
		try {
			this.systemUserService.doEdit(systemUser, roleIds);
			j.setMsg("编辑成功");
		} catch (Exception e) {
			log.info(e.getMessage());
			j.setSuccess(false);
			j.setMsg("编辑失败");
		}
		return j;
	}

	@RequestMapping(value = { "doDelete" }, method = { org.springframework.web.bind.annotation.RequestMethod.GET })
	@ResponseBody
	public AjaxJson doDelete(@RequestParam(required = true, value = "id") Long id) {
		AjaxJson j = new AjaxJson();
		try {
			this.systemUserService.doDelete(id);
			j.setMsg("删除成功");
		} catch (Exception e) {
			log.info(e.getMessage());
			j.setSuccess(false);
			j.setMsg("删除失败:" + e.getMessage());
		}
		return j;
	}
}

